import 'dart:convert';
import 'package:commons/commons.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

extension StorageEx on GetInterface {
  Storage get storage => Get.find<Storage>();
}

class Storage extends GetxController {
  late final SharedPreferences _prefs;

  Future<void> initializtion() async {
    _prefs = await SharedPreferences.getInstance();
  }

  Future<bool> set(String key, dynamic value) {
    if (value is bool) {
      return _prefs.setBool(key, value);
    } else if (value is int) {
      return _prefs.setInt(key, value);
    } else if (value is double) {
      return _prefs.setDouble(key, value);
    } else if (value is String) {
      return _prefs.setString(key, value);
    } else if (value is List<String>) {
      return _prefs.setStringList(key, value);
    } else {
      return Future.error(false);
    }
  }

  Future<bool> setJson(String key, JSON json) {
    return _prefs.setString(key, jsonEncode(json));
  }

  Future<bool> setJsonList(String key, List<JSON> json) {
    return _prefs.setString(key, jsonEncode(json.map((e) => e)));
  }

  T? get<T>(String key) {
    dynamic value = _prefs.get(key);
    if (value is T) {
      return value;
    } else {
      ILog.d('Expected type $T, but got ${value.runtimeType}');
      return null;
    }
  }

  T? getModel<T>(String key, T Function(JSON) fromJson) {
    String? jsonString = _prefs.getString(key);
    try {
      return fromJson(jsonString?.parm ?? {});
    } catch (e) {
      return null;
    }
  }

  List<T>? getModelList<T>(String key, T Function(JSON) fromJson) {
    String? jsonString = _prefs.getString(key);
    try {
      List<JSON> jsonList = jsonString?.jsonList<JSON>() ?? [];
      return jsonList.map((e) => fromJson(e)).toList();
    } catch (e) {
      return null;
    }
  }

  Future<bool> remove(String key) {
    return _prefs.remove(key);
  }
}
